package middleware

import (
	"net/http"

	"gitee.com/daonna/collab-manage-system/pkg/consts"
	"gitee.com/daonna/collab-manage-system/pkg/e"
	"gitee.com/daonna/collab-manage-system/pkg/util"

	"github.com/gin-gonic/gin"
)

// AuthMiddleware token验证中间件
func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		var code int
		code = e.Success

		// 从请求头获取 token
		accessToken := c.GetHeader(consts.AccessTokenHeader)
		refreshToken := c.GetHeader(consts.RefreshTokenHeader)

		if accessToken == "" {
			code = e.InvalidParams
			c.JSON(http.StatusOK, gin.H{
				"status": code,
				"msg":    e.GetMsg(code),
				"data":   "Token不能为空",
			})
			c.Abort()
			return
		}

		// 验证并刷新 token
		newAccessToken, newRefreshToken, err := util.ParseRefreshToken(accessToken, refreshToken)
		if err != nil {
			code = e.ErrorAuthToken
			c.JSON(http.StatusOK, gin.H{
				"status": code,
				"msg":    e.GetMsg(code),
				"data":   err.Error(),
			})
			c.Abort()
			return
		}

		// 验证新的 access token
		claims, err := util.ParseToken(newAccessToken)
		if err != nil {
			code = e.ErrorAuthToken
			c.JSON(http.StatusOK, gin.H{
				"status": code,
				"msg":    e.GetMsg(code),
				"data":   err.Error(),
			})
			c.Abort()
			return
		}

		// 设置新的 token 到响应头
		c.Header(consts.AccessTokenHeader, newAccessToken)
		c.Header(consts.RefreshTokenHeader, newRefreshToken)

		// 将用户信息存入上下文
		c.Set("user_id", claims.ID)
		c.Set("username", claims.UserName)
		c.Next()
	}
}
